import access from '@/access'
import type { AccessUser } from '@/types/services'
import type { RouteRecordRaw, Router } from 'vue-router'

const views = import.meta.glob('@/views/**/*View.vue')

export const getImportComponent = (path: string) => {
  return views[`/src/views/${path}.vue`]
}

/**
 * 思路：把所有路由写出来，然后根据 access 筛选有权限的路由进行动态添加到 router 中
 */
const routes = [
  {
    path: 'home',
    name: 'home',
    component: getImportComponent('home/HomeView'),
    access: 'canReadHomeView',
    children: []
  },
  {
    path: 'role',
    name: 'role',
    component: 'role/RoleView',
    access: 'canReadRoleView',
    children: []
  },
  {
    path: 'role/save/:id',
    name: 'role-save',
    component: 'role/SaveView',
    access: 'canReadRoleSaveView',
    children: []
  },
  {
    path: 'role/add',
    name: 'role-add',
    component: 'role/SaveView',
    access: 'canReadRoleAddView',
    children: []
  },
  {
    path: 'user',
    name: 'user',
    component: 'user/UserView',
    access: 'canReadUserView',
    children: []
  },
  {
    path: 'user/save/:id',
    name: 'user-save',
    component: 'user/SaveView',
    access: 'canReadUserSaveView',
    children: []
  },
  {
    path: 'user/add',
    name: 'user-add',
    component: 'user/SaveView',
    access: 'canReadUserAddView',
    children: []
  },
  {
    path: 'permission',
    name: 'permission',
    component: 'permission/PermissionView',
    access: 'canReadPermissionView',
    children: []
  },
  {
    path: 'permission/save/:id',
    name: 'permission-save',
    component: 'permission/SaveView',
    access: 'canReadPermissionSaveView',
    children: []
  },
  {
    path: 'permission/add',
    name: 'permission-add',
    component: 'permission/SaveView',
    access: 'canReadPermissionAddView',
    children: []
  }
]

export default (router: Router, user: AccessUser): RouteRecordRaw[] => {
  const accesses = access(user)

  const routeMap: Record<string, RouteRecordRaw> = {}
  const routes: RouteRecordRaw[] = []

  Object.entries(views)
    .filter(([key]) => {
      const path = key.slice(11, -8).toLocaleLowerCase()
      return accesses[path]
    })
    .forEach(([key, value]) => {
      const path = key.slice(11, -8).toLocaleLowerCase()
      const dirs = path.split('/').slice(0, -1)
      if (dirs.length === 0) {
        router.addRoute({
          path,
          name: path,
          component: value,
          children: []
        })
        return
      }
      dirs.forEach((dir) => {
        router.addRoute(dir, {})
      })
      return {
        path,
        name: path,
        component: value,
        children: []
      }
    })
  return
}
